<?php

  if (!function_exists('add_action'))
  {
      require_once("../../../wp-config.php");
  }

class AjaxChat {
	public $frequency = 10;
	public $pagesize = 10;
    public $r_page=1;
    public $offset=0;
    public $r_day='';

    function __construct() {
        global $wpdb;
        $this->db=$wpdb;
		date_default_timezone_set('Europe/Berlin');
    }

    public function process() {

        $this->pageCount();
        if($_POST['message']!='')
            $this->InsertMessage();
        elseif(!empty($_POST['private_message']))
            $this->privateInsert();
		elseif(!empty($_GET['r_id']))
			$this->add_rating($_GET['r_id']);
		elseif((int)$_GET['record_channel_id']!='')
            $this->recordChannelHide();
        else
            $this->ShowMessage();

    }
    public function recordChannelHide()
    {
        // Get current user info
         $current_info=wp_get_current_user();

        $current_id=$current_info->id;

        // Get the GET record_channel_id
        $channel_id=$_GET['record_channel_id'];

        // get current record in the database
        $channels=$this->db->get_var("SELECT channel_hide FROM `wp_users` WHERE id='".$current_id."'");

        $channels.=','.$channel_id;

        $sql="update `wp_users` set `channel_hide`='".$channels."' where id='".$current_id."'";

        $this->db->query($sql);

    }
    public function pageCount() {

        if(isset($_GET['r_page']))
        {
            $this->pagesize=10;

            $this->r_page=isset($_GET['r_page'])?(int)$_GET['r_page']:1;

            $this->offset=($this->r_page-1)*$this->pagesize;
        }
    }
#############################  MAIN FUNCTION ################################
    public function InsertMessage() {
        //current user info and the message content
        $u_current_content=array();

        //$current_site=get_current_site();
        $user_infos=wp_get_current_user();

        if(is_null($user_infos->display_name))
        {
            echo "Error";
            exit;
        }

        $m_message=addslashes(htmlspecialchars($_POST['message']));
        $chat_room_id=isset($_POST['chat_room_id'])?(int)$_POST['chat_room_id']:0;
        if($chat_room_id==0)
            $receiver_id=isset($_POST['receiver_id'])?(int)$_POST['receiver_id']:0;
        else
            $receiver_id=$chat_room_id;

        $anony=(!empty($_POST['anonymously']))?1:0;

        $u_id=is_null($user_infos->id)?0:$user_infos->id;
        if($profileuser = $this->get_user_info($u_id))
		{
			$u_profiler = $profileuser->first_name."-".$profileuser->last_name;
			$u_name = $profileuser->display_name;
		}
		else
		{
			$u_profiler = '';
			$u_name = 'Guest';
		}

        //retrieve the chatroom color
        $color = $this->getChatroom($chat_room_id)->color;

		$table_name = $this->db->prefix . "chat";
        $sql=sprintf("INSERT INTO $table_name(`id`,`chat_room_id`,`text`,`timestamp`,`sender_id`,`receiver_id`,`rating`,`anonymous`) value(null,'%d','%s',now(),'%d','%d','%d','%d')",$chat_room_id,$m_message,$u_id,0,0,$anony);

        //input the $u_current_content
        $u_current_content['u_id']=$u_id;
        $u_current_content['u_name']=($anony==1)?'':$u_name;
        $u_current_content['content']=stripslashes(nl2br(htmlspecialchars($_POST['message'])));
		$default_icon = get_bloginfo('wpurl')."/wp-content/plugins/wp-livechat/style/img/pic.gif";
        $u_current_content['u_img']=userphoto__get_userphoto($u_id,2,'','',array(), $default_icon);
        $u_current_content['color']=$color;
        $u_current_content['channel']=$chat_room_id;
        $u_current_content['anonymous']=$anony;
		$u_current_content['time']=date("D M d, h:i A",time());
		$u_current_content['profiler'] = $u_profiler;

        $u_current_content=json_encode($u_current_content);

        if($this->db->query($sql))
        {
            echo $u_current_content;
        }
    }

    public function privateInsert() {

        //private content array for changing to json
        $private_content=array();

        $user_infos=wp_get_current_user();

        if(is_null($user_infos->display_name))
        {
            echo "Error";
            exit;
        }

        // retrieve the client post message
        $p_message=addslashes(htmlspecialchars($_POST['private_message']));
        $receiver_id=isset($_POST['receiver_id'])?(int)$_POST['receiver_id']:0;

        // retrieve the user info
        $u_id=is_null($user_infos->id)?0:$user_infos->id;
		if($profileuser = $this->get_user_info($u_id))
		{
			$u_profiler = $profileuser->first_name."-".$profileuser->last_name;
			$u_name = $profileuser->display_name;
		}
		else
		{
			$u_profiler = '';
			$u_name = 'Guest';
		}
        //generate the sql
        $table_name = $this->db->prefix . "chat";
        $sql=sprintf("INSERT INTO $table_name(`id`,`chat_room_id`,`text`,`timestamp`,`sender_id`,`receiver_id`,`rating`) value(null,'%d','%s',now(),'%d','%d','%d')",0,$p_message,$u_id,$receiver_id,0);

        // generate the private content for the client DOM insert
        $private_content['u_id']=$u_id;
        $private_content['u_name']=$u_name;
        $private_content['content']=stripslashes(nl2br(htmlspecialchars($_POST['private_message'])));
		$default_icon = get_bloginfo('wpurl')."/wp-content/plugins/wp-livechat/style/img/pic.gif";
		$private_content['u_img'] = userphoto__get_userphoto($u_id,2,'','',array(), $default_icon);
		$private_content['time']=date("D M d, h:i A",time());
		$private_content['profiler'] = $u_profiler;
        // encode the $private_content
        $private_content=json_encode($private_content);

        // execute the sql and make sure the message head inserted into database
        if($this->db->query($sql))
        {
            echo $private_content;
        }

    }

    public function ShowMessage() {
        $last_id=$_GET['last_id'];
        $current_info=wp_get_current_user();
		$u_id = $current_info->data->ID;
		$table_name = $this->db->prefix . "chat";
        $today = date('Y-m-d',time());
		if($_GET['operation'] == 'init')
		{
        	$sql="SELECT * FROM $table_name WHERE `chat_room_id` != 0 AND SUBSTRING(`timestamp`,1,10) ='$today' order by `timestamp` desc limit 0,10";
		}
		elseif($_GET['operation'] == 'init_private')
		{
				$sql="SELECT * FROM $table_name WHERE ";
				if($_GET['sender'] != '')
				{
					$sender = $_GET['sender'];
					$sql .= "`sender_id` = $sender AND ";
				}
				$sql .= "`receiver_id` = $u_id AND DATE_FORMAT(`timestamp`,'%e') = DATE_FORMAT(now(),'%e') AND `chat_room_id` = 0 order by timestamp desc limit 0,10";
		}
		elseif($_GET['operation'] == 'private')
		{
			$sql="SELECT * FROM $table_name WHERE `receiver_id` = $u_id AND UNIX_TIMESTAMP(`timestamp`) >= UNIX_TIMESTAMP( now()) - $this->frequency AND `chat_room_id` = 0 order by timestamp desc";
		}
		elseif($_GET['operation'] == 'show_rec')
		{
				$day = $_GET['day'];
                if(!empty($_GET['r_day']))
                {
                    $day=$_GET['r_day'];
                }
                $c_day=$day;
				$day = date('Y-m-d',$day);
				$today = date('Y-m-d',time());

				if($day != $today){
                    $sql="SELECT count(*) FROM $table_name WHERE `chat_room_id` != 0 AND SUBSTRING(`timestamp`,1,10) ='$day'";
                    $res=$this->db->get_row($sql,ARRAY_A);
                    $res=$res['count(*)'];
					$options = get_option("live_chat");
                    if($res<=20 && $c_day<strtotime(date('y-m-d',time())) && $options['static_mess_record'])
                    {
                        $sql="SELECT * FROM $table_name WHERE `chat_room_id` != 0 AND SUBSTRING(`timestamp`,1,10) <= '$day' order by timestamp desc limit 0,20";

                    }else{
					    $sql="SELECT * FROM $table_name WHERE `chat_room_id` != 0 AND SUBSTRING(`timestamp`,1,10) = '$day' order by timestamp desc limit $this->offset,$this->pagesize";//LIMIT ($page-1)*$pagesize , $pagesize
                    }

				}
				else{
					$sql="SELECT * FROM $table_name WHERE `chat_room_id` != 0 AND SUBSTRING(`timestamp`,1,10) = '$day' order by timestamp desc limit $this->offset,$this->pagesize";
                    }

		}
		elseif($_GET['operation'] == 'show_rec_private')
		{
			$receiver = $_GET['receiver'];
			$day = $_GET['day'];
            if(!empty($_GET['r_day']))
            {
                    $day=$_GET['r_day'];
            }
			$day = date('Y-m-d',$day);

			$today = date('Y-m-d',time());
			if($day != $today){

				if($receiver == '')
				{
					$sql="SELECT * FROM $table_name WHERE `receiver_id` = $u_id AND SUBSTRING(`timestamp`,1,10) = '$day' AND `chat_room_id` = 0 order by timestamp desc limit $this->offset,$this->pagesize";
				}
				else
				{
					$sql="SELECT * FROM $table_name WHERE SUBSTRING(`timestamp`,1,10) = '$day' AND `chat_room_id` = 0 AND ((`receiver_id` = $u_id AND `sender_id` = $receiver) OR (`receiver_id` = $receiver AND `sender_id` = $u_id)) order by timestamp desc limit $this->offset,$this->pagesize";
				}
			}
			else{
				if($receiver == '')
				{

					$sql="SELECT * FROM $table_name WHERE `receiver_id` = $u_id AND SUBSTRING(`timestamp`,1,10) = '$day' AND `chat_room_id` = 0 order by timestamp desc limit $this->offset,$this->pagesize";
				}
				else
				{
					$sql="SELECT * FROM $table_name WHERE SUBSTRING(`timestamp`,1,10) = '$day' AND `chat_room_id` = 0 AND ((`receiver_id` = $u_id AND `sender_id` = $receiver) OR (`receiver_id` = $receiver AND `sender_id` = $u_id)) order by timestamp desc limit $this->offset,$this->pagesize";
				}
			}
		}
		elseif($_GET['operation'] == 'current_chat'){
               $day = date('Y-m-d',$_GET['r_day']);
               $sql="SELECT * FROM $table_name WHERE `chat_room_id` != 0 and SUBSTRING(`timestamp`,1,10)='$day' AND `id`<'$last_id' order by timestamp desc limit 0,10";
        }elseif($_GET['operation']=='private_current'){
            $day = date('Y-m-d',$_GET['r_day']);
            $p_last_id=$_GET['p_last_id'];
            $sql="SELECT * FROM $table_name WHERE `receiver_id` = $u_id and `chat_room_id` = 0 and SUBSTRING(`timestamp`,1,10)='$day' AND `id`<'$p_last_id' order by timestamp desc limit 0,10";

        }
        else
		{
			$room_condition = '';
			if($_GET['chatroom'])
			{
				$room_condition=" AND ( ";
				$chatroom = split(",",$_GET['chatroom']);
				$_i=count($chatroom);
				foreach($chatroom as $index=>$room_item)
				{
					if ($index != ($_i-1))
					{
						$room_condition .= "`chat_room_id` = $room_item OR " ;
					}
					else
					{
						$room_condition .= " `chat_room_id` = $room_item )" ;
					}
				}
			}
			$sql="SELECT * FROM $table_name WHERE `sender_id` <> $u_id AND UNIX_TIMESTAMP(`timestamp`) >= UNIX_TIMESTAMP( now()) - $this->frequency AND `chat_room_id` != 0 ".$room_condition."order by timestamp desc";
		}
        $result=$this->db->get_results($sql,ARRAY_A);
		if($result)
		{

			$current_time = $this->getMysqlTime();
			foreach($result as $index=>$user)
			{
				$mess_id[$index] = $user[$index]['id'];
				//get icon html
				//$result[$index]['icon'] = get_avatar( $result[$index]['sender_id'], $size = '46', $default = '<path_to_url>' );

				if($result[$index]['anonymous'] == 0)
				{
					$default_icon = get_bloginfo('wpurl')."/wp-content/plugins/wp-livechat/style/img/pic.gif";
					$result[$index]['icon'] = userphoto__get_userphoto($result[$index]['sender_id'],2,'','',array(), $default_icon);
				}
				if($result[$index]['anonymous'] == 1)
    			{
					$iconurl = get_bloginfo('wpurl')."/wp-content/plugins/wp-livechat/style/img/pic.gif";
        			$result[$index]['icon'] = "<img class='photo' src='".$iconurl."' width='46' height='46'/>";
    			}
				$temp_id[$index] = $user['id'];
				$chat_room_id = $result[$index]['chat_room_id'];
				$color = $this->getChatroom($chat_room_id)->color;
				$result[$index]['color'] = $color;

				$result[$index]['room_id'] = $chat_room_id;

				$msgtime = strtotime($result[$index]['timestamp']);
				//$time = $this->comparetime($current_time,$msgtime);
				$time = date("D M d, h:i A",$msgtime);
				$result[$index]['time'] = $time;
                $result[$index]['text']=stripslashes(nl2br(($result[$index]['text'])));
				if($profileuser = $this->get_user_info($user['sender_id']))
				{
					$result[$index]['profiler'] = $profileuser->first_name."-".$profileuser->last_name;
					$result[$index]['username'] = $profileuser->display_name;
				}
				else
				{
					$result[$index]['profiler'] = '';
					$result[$index]['username'] = 'Guest';
				}
			}

		}
        echo (json_encode($result));
    }
	public function add_rating($id)
	{
		$table_name = $this->db->prefix . 'chat';
		$sql="UPDATE $table_name SET `rating` = `rating` +1 WHERE `id` =$id LIMIT 1";
		require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
		if($this->db->query($sql))
		{
			echo "Success";
		}

	}
############################## USEFUL FUNCTION ##################################
	public function get_user_info( $user_id ) {
		$user = new WP_User( $user_id );
		$user->user_login   = attribute_escape($user->user_login);
		$user->user_email   = attribute_escape($user->user_email);
		$user->user_url     = clean_url($user->user_url);
		$user->first_name   = attribute_escape($user->first_name) ? attribute_escape($user->first_name) : 'firstname';
		$user->last_name    = attribute_escape($user->last_name) ? attribute_escape($user->last_name) : 'lastname';
		$user->display_name = attribute_escape($user->display_name);
		$user->nickname     = attribute_escape($user->nickname);
		$user->aim          = isset( $user->aim ) && !empty( $user->aim ) ? attribute_escape($user->aim) : '';
		$user->yim          = isset( $user->yim ) && !empty( $user->yim ) ? attribute_escape($user->yim) : '';
		$user->jabber       = isset( $user->jabber ) && !empty( $user->jabber ) ? attribute_escape($user->jabber) : '';
		$user->description  = isset( $user->description ) && !empty( $user->description ) ? wp_specialchars($user->description) : '';
		return $user;
	}
	public function getMysqlTime()
	{
		$table_name = $this->db->prefix . 'chat';
		$sql="SELECT UNIX_TIMESTAMP( now())";
		$result=$this->db->get_results($sql,ARRAY_N);
		return $result[0][0];
	}
	public function getChatroom($chat_room_id)
	{
		//retrieve the chatroom color
        $table_name=$this->db->prefix."chatroom";
        $sql="select * from $table_name where `chat_room_id`='".$chat_room_id."'";
        $chat_room=$this->db->get_results($sql);
        $chat_room=$chat_room[0];
		return $chat_room;
	}
	public function comparetime($current_time,$msg_time)
	{
		$current_time_int = date("ymdHis",$current_time);
		$msg_time_int = date("ymdHis",$msg_time);
		$current_time_day = substr($current_time_int , 1 , 6);
		$msg_time_day = substr($msg_time_int , 1 , 6);
		if ($current_time_day - $msg_time_day < 1)
		{
			if (($current_time - $msg_time) < 60)
			{
				return '30 sec ago';
			}
			elseif (3600 > ($current_time - $msg_time) && ($current_time - $msg_time) >= 60)
			{
				return '30 min ago';
			}
			elseif (86400 > ($current_time - $msg_time) && ($current_time - $msg_time) >= 3600)
			{
				return floor(($current_time - $msg_time)/3600)." hour ago";
			}
		}
		elseif( 2 > ($current_time_day - $msg_time_day) && ($current_time_day - $msg_time_day) > 1)
		{
			return "Yesterday  ".date("h:i A", $msg_time);
		}
		else
		{
			return date("D M d, h:i A",$msg_time);
		}
	}

    /*public function styleMessage($messages) {

        $message_content='';
        foreach($messages as $comment)
        {
               $message_content.="<li>";
			   $message_content.="<div class=\"user\">";
               $message_content.="<img src=\"".get_bloginfo('wpurl')."/wp-content/plugins/wp-livechat/style/img/pic.gif"."\" width=\"46\" height=\"46\">";
               $message_content.="<div class=\"text\">";
               $message_content.="<a href=\"#\">".$comment->sender_id."</a><span>".$comment->text."</span>";
               $message_content.="<ul class=\"info\">";
               $message_content.="<li class=\"clock\">".$comment->timestamp."</li>";
               $message_content.="<li class=\"important\">Important to me</li>";
               $message_content.='<li class="pic"><img src="'.get_bloginfo('wpurl').'/wp-content/plugins/wp-livechat/style/img/x1.gif" width="14" height="14" /></li>';
               $message_content.="</ul>";
			    $message_content.="</div>";
			   $message_content.="<div class=\"clear\"></div>";
               $message_content.="</div>";
               $message_content.="</li>";
        }

        return $message_content;
    }*/

}
$AjaxChat=new AjaxChat();
$AjaxChat->process();



?>